<template>
  <div class="user-register-main">
    <div class="head">法人注册</div>
    <el-form class="form-main" ref="ruleFormRef" :model="formData">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
            label="核验类型"
            :rules="$validate.required()"
            prop="legalPerType"
          >
            <Aselect
              v-model="formData.legalPerType"
              :options="registerDict.companyCheckType"
              @change="formData.paperType = '111'"
            />
          </el-form-item>
        </el-col>
         <!-- TODO 长度待确定 -->
        <el-col :span="12">
          <el-form-item
            label="名称"
            :rules="$validate.maxLength(true, 0, 30)"
            prop="bussName"
          >
            <el-input
              v-model="formData.bussName"
              :placeholder="namePlaceholder"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="统一社会信用代码"
            :rules="
              formData.legalPerType === '4'
                ? $validate.required()
                : $validate.societyCode(true)
            "
            prop="creditCode"
          >
            <el-input
              v-model="formData.creditCode"
              :placeholder="`请输入统一社会信用代码${
                this.formData.legalPerType === '4' ? '/组织号' : ''
              }`"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="法定代表人证件类型"
            :rules="$validate.required()"
            prop="paperType"
          >
            <Aselect v-model="formData.paperType" :options="frOptions" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="姓名"
            :rules="$validate.realName(true)"
            prop="realname"
          >
            <el-input v-model="formData.realname" placeholder="请输入姓名">
            </el-input>
          </el-form-item>
        </el-col>
        <template v-if="frOptions[0] && formData.paperType === frOptions[0].value">
          <el-col :span="12">
            <el-form-item
              label="身份证号"
              :rules="$validate.IDcode(true)"
              prop="paperCode"
            >
              <el-input
                v-model="formData.paperCode"
                placeholder="请输入身份证号"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="身份证有效期开始时间"
              :rules="$validate.required()"
              prop="paperStartTime"
            >
              <AdatePicker
                v-model="formData.paperStartTime"
                placeholder="请选择身份证有效开始时间"
                @change="
                  datePrescription !== 999 &&
                    (formData.paperEndTime = $dayjs(formData.paperStartTime)
                      .add(datePrescription, 'year')
                      .format('YYYY-MM-DD'))
                "
                :clearable="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- :rules="datePrescription !== 999 && $validate.required()" -->
            <el-form-item label="身份证有效期结束时间" prop="paperEndTime">
              <AdatePicker
                v-model="formData.paperEndTime"
                placeholder=""
                @change="
                  formData.paperStartTime = $dayjs(formData.paperEndTime)
                    .subtract(datePrescription, 'year')
                    .format('YYYY-MM-DD')
                "
                :clearable="false"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证时效">
              <Aradio
                v-model="datePrescription"
                :options="[
                  { label: '5年', value: 5 },
                  { label: '10年', value: 10 },
                  { label: '20年', value: 20 },
                  { label: '长期有效', value: 999 },
                ]"
                @change="datePrescriptionChange()"
              />
            </el-form-item>
          </el-col>
        </template>
        <template v-if="frOptions[1] && formData.paperType === frOptions[1].value">
          <el-col :span="12">
            <el-form-item
              label="中国护照编号"
              :rules="$validate.required()"
              prop="paperCode"
            >
              <el-input
                v-model="formData.paperCode"
                placeholder="请输入中国护照编号"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </template>
        <template v-if="frOptions[2] && formData.paperType === frOptions[2].value">
          <el-col :span="12">
            <el-form-item
              label="台湾居民来往大陆通行证编号"
              :rules="$validate.required()"
              prop="paperCode"
            >
              <el-input
                v-model="formData.paperCode"
                placeholder="请输入台湾居民来往大陆通行证编号"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </template>
        <template v-if="frOptions[3] && formData.paperType === frOptions[3].value">
          <el-col :span="12">
            <el-form-item
              label="港澳居民来往内地通行证编号"
              :rules="$validate.required()"
              prop="paperCode"
            >
              <el-input
                v-model="formData.paperCode"
                placeholder="请输入港澳居民来往内地通行证编号"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </template>
        <template v-if="frOptions[4] && formData.paperType === frOptions[4].value">
          <el-col :span="12">
            <el-form-item
              label="外国人永久居留证或永久居留许可编号"
              :rules="$validate.required()"
              prop="paperCode"
            >
              <el-input
                v-model="formData.paperCode"
                placeholder="请输入外国人永久居留证或永久居留许可编号"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="国家或地区"
              :rules="$validate.required()"
              prop="country"
            >
              <Aselect
                v-model="formData.country"
                :options="registerDict.country"
              />
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="12">
          <el-form-item
            label="账号"
            :rules="$validate.maxLength(true, 6, 20)"
            prop="username"
          >
            <el-input
              v-model="formData.username"
              placeholder="请输入账号,6~20个字符"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="手机号"
            :rules="$validate.phone(true)"
            prop="phone"
          >
            <el-input
              autocomplete="new-password"
              v-model="formData.phone"
              placeholder="请输入法定代表人或企业联系人手机号"
            >
              <!-- <template slot="append">
                <el-button type="primary" size="small" @click="getCode">获取验证码</el-button>
              </template> -->
            </el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item
            label="验证码"
            :rules="$validate.required()"
            prop="smsCode"
          >
            <el-input v-model="formData.smsCode" placeholder="请输入验证码">
            </el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item
            label="密码"
            :rules="$validate.password(true)"
            prop="password"
          >
            <el-input
              autocomplete="new-password"
              v-model="formData.password"
              :type="passwordFocus ? 'password' : 'text'"
              @focus="passwordFocus = true"
              placeholder="8-18位数字、大小写字母、符号3种及以上组成"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="确认密码"
            :rules="confirmPasswordRules"
            prop="confirmPassword"
          >
            <el-input
              autocomplete="new-password"
              v-model="formData.confirmPassword"
              @focus="passwordFocus = true"
              :type="passwordFocus ? 'password' : 'text'"
              placeholder="请输入确认密码"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="foot">
      <div class="btn-register" @click="submit">注册</div>
      <div class="btn-login" @click="$emit('login')">已有账号去登录</div>
    </div>
  </div>
</template>
<script>
import Aselect from '@/components/Select/Aselect';
import AdatePicker from '@/components/TimePicker/AdatePicker';
import Aradio from '@/components/Radio/Aradio';
import registerDict from '@/assets/js/registerDict.js';
import userApi from '@/api/user';
export default {
  components: {
    Aselect,
    AdatePicker,
    Aradio,
  },
  data() {
    return {
      passwordFocus: false,
      formData: {
        legalPerType: '1',
        paperType: '111',
      },
      datePrescription: 5,
    };
  },
  computed: {
    confirmPasswordRules() {
      return [
        {
          required: true,
          message: '不能为空!',
          trigger: ['blur'],
        },
        {
          validator: (rule, value, callback) => {
            if (value !== this.formData.password) {
              callback(new Error('两次输入密码不一致!'));
            } else {
              callback();
            }
          },
          trigger: ['blur'],
        },
      ];
    },
    namePlaceholder() {
      let result;
      this.registerDict.companyCheckType.forEach((item) => {
        if (this.formData.legalPerType === item.value) {
          result = item.namePlaceholder;
        }
      });
      return '请输入' + result;
    },
    frOptions() {
      const arr = this.registerDict.companyDocumentType;
      if (this.formData.legalPerType === '2') {
        return arr.slice(0, -1);
      } else if (
        this.formData.legalPerType === '3' ||
        this.formData.legalPerType === '4'
      ) {
        return arr.slice(0, 1);
      } else {
        return arr;
      }
    },
    registerDict() {
      return registerDict;
    },
  },
  methods: {
    init() {
      this.formData = {
        legalPerType: '1',
        paperType: '111',
      };
      this.$refs.ruleFormRef.clearValidate();
    },
    datePrescriptionChange() {
      if (this.datePrescription === 999) {
        this.formData.paperEndTime = null;
      } else {
        if (this.formData.paperStartTime) {
          this.formData.paperEndTime = this.$dayjs(this.formData.paperStartTime)
            .add(this.datePrescription, 'year')
            .format('YYYY-MM-DD');
        }
      }
    },
    async getCode() {
      let goOn = true;
      await this.$refs.ruleFormRef.validateField(['phone'], (errorMessage) => {
        if (errorMessage) {
          goOn = false;
          this.$message.error('请先输入正确的手机号！');
        }
      });
      if (goOn) {
        let params = {
          userType: 2,
          username: this.formData.phone,
          mode: 1,
        };
        const { phone } = await userApi.getCode(params);
        const tel = phone.substr(0, 3) + '****' + phone.substr(-4, 4);
        this.$notify({
          title: '提示',
          message: `验证码已发送至${tel}手机上，请注意查收!`,
          type: 'success',
        });
      }
    },
    async submit() {
      try {
        await this.$validate.checkValidate(this.$refs.ruleFormRef);
        let params = {
          ...this.formData,
          userType: 2,
        };
        await userApi.register(params);
        this.$message.success('注册成功');
        this.$emit('login');
      } catch (error) {
        console.log(error);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.user-register-main {
  position: relative;
  margin-top: 60px;
  width: 806px;
  height: 857px;
  padding: 50px 70px 70px 70px;
  background: url('~@/assets/img/login/register_bg.png') 100% 100% no-repeat;
  background-position: center;
  .head {
    font-size: 30px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #333333;
    text-align: center;
  }
  .foot {
    position: absolute;
    left: 0px;
    bottom: 60px;
    width: 100%;

    .btn-register {
      margin: auto;
      width: 470px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      color: #fff;
      font-size: 18px;
      background: url('~@/assets/img/login/btn_bg.png') 100% 100% no-repeat;
      background-position: center;
      border-radius: 4px;
      cursor: pointer;
    }
    .btn-login {
      margin: auto;
      margin-top: 20px;
      width: 470px;
      height: 40px;
      line-height: 40px;
      font-size: 18px;
      color: #3c8cf1;
      border-radius: 4px;
      border: 1px solid #3c8cf1;
      text-align: center;
      cursor: pointer;
    }
  }
}
::v-deep {
  .el-input-group__append {
    .el-button--primary {
      color: #fff;
      background-color: #3c8cf1;
      height: 30px;
    }
  }
}
</style>
